import 'package:flutter/material.dart';
import '../../base/MyScaffold.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';
import 'package:get/get.dart';

import '../../res.dart';
import '../../sqflite/CreateTableSqls.dart';
import '../../sqflite/DBUtil.dart';
import '../../utils/Tool/MyUtilsTools.dart';
import '../../utils/color/ColorUtils.dart';
import 'SearchList.dart';

class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);

  @override
  State<Search> createState() => _searchState();
}

class _searchState extends State<Search> {
  String search = "";
  TextEditingController controller = TextEditingController();

  List<String> list = [];
  DBUtil? dbUtil;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dbUtil = DBUtil();

    getData();
  }

  void submit(value) async {
    if (MyUtilsTools.stringIsEmpty(value)) {
      return;
    }
    setState(() {});
    Get.to(SearchList(
      search: value,
    ));

    if (list.contains(value)) {
      return;
    }
    list.add(value);
    await dbUtil!.open();
    Map<String, dynamic> paramters = <String, dynamic>{};
    paramters["name"] = value;
    dbUtil?.insertByHelper(history, paramters);
  }

  getData() async {
    await dbUtil!.open();
    await dbUtil!.query(history).then((value) {
      for (Map<String, dynamic> map in value) {
        list.add(map["name"]);
      }
      setState(() {});
    });
  }

  delete() async {
    await dbUtil!.open();
    await dbUtil?.deleteByHelper(history);
  }

  deleteBy(String name) async {
    await dbUtil!.open();
    await dbUtil
        ?.deleteByHelper(history, whereStr: 'name=?', whereArgs: [name]);
  }

  List<Widget> getWrap(List<String> list) {
    List<Widget> widgets = [];
    for (String item in list) {
      widgets.add(GestureDetector(
        onTap: () {
          Get.to(SearchList(
            search: item,
          ));
        },
        onLongPress: () {
          deleteBy(item);
          this.list.removeWhere((element) => item == element);
          setState(() {});
        },
        child: TextView(
          item,
          style: TextStyle(color: rgba(100, 101, 102, 1)),
          borderColor: rgba(247, 247, 247, 1),
          backcolor: rgba(247, 247, 247, 1),
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
          radius: BorderRadius.circular(6),
        ),
      ));
    }
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      navBarHide: true,
      body: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Container(
                      height: 44,
                      padding: const EdgeInsets.only(left: 10),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6),
                          color: rgba(247, 248, 250, 1)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const MyLocalImage(
                            Res.nav_icon_search,
                            width: 20,
                            height: 20,
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          Expanded(
                            child: TextField(
                              controller: controller,
                              onChanged: (v) {
                                setState(() {
                                  search = v;
                                });
                              },
                              onSubmitted: (v) {
                                submit(v);
                              },
                              textInputAction: TextInputAction.search,
                              decoration: InputDecoration(
                                suffixIcon: Container(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 14, horizontal: 16),
                                  child: Offstage(
                                    offstage: search.isEmpty ? true : false,
                                    child: InkWell(
                                      onTap: () {
                                        controller.clear();
                                        setState(() {
                                          search = "";
                                        });
                                      },
                                      child: Container(
                                        child: const MyLocalImage(
                                          Res.sys_icon_delete_grey3x,
                                          width: 10,
                                          height: 10,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                border: InputBorder.none,
                                hintText: 'search_files'.tr,
                                hintStyle:
                                    TextStyle(color: rgba(200, 202, 204, 1)),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  TextView(
                    "cancel".tr,
                    padding: const EdgeInsets.only(left: 20),
                    style: TextStyle(color: ColorUtils.text),
                    onclick: () {
                      Get.back();
                    },
                  )
                ],
              ),
              if (list.isNotEmpty)
                Container(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  child: Row(
                    children: [
                      TextView("search_history".tr),
                      const Spacer(),
                      TextView(
                        "clean".tr,
                        onclick: () {
                          delete();
                          list.clear();
                          setState(() {});
                        },
                      ),
                    ],
                  ),
                ),
              Wrap(
                alignment: WrapAlignment.start,
                direction: Axis.horizontal,
                spacing: 10,
                // 子组件之间的间距
                runSpacing: 10,
                // 换行之间的间距
                children: getWrap(list),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
